import re
from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend
from rest_framework_jwt.utils import jwt_decode_handler


from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    print(jwt_decode_handler(token))
    return {
        "token": token,
        "user": user.username,
        "user_id": user.pk
    }


def get_user_by_account(account):
    """
    通过传入的账户动态获取user 模型对象
    :param account:
    :return: user模型对象或None
    """

    try:
        if re.match(r'1[3-9]\d{9}$', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    """修改django的认证类,为了实现多账号登录"""

    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_by_account(username)
        if user and user.check_password(password):
            return user
